import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import { mapActions } from 'vuex'

Vue.use(VueRouter)

const routes = [
  {
    path: '/', // 网页打开的默认路径
    component: () => import('@/views/layout/index.vue'),
    // 因为默认在/页面，没有匹配到/home，在进入/页面后要进行路由重定向
    redirect: '/home', // 会导致路由规则数组再次匹配
    children: [
      {
        path: 'home',
        component: () => import('@/views/home/index.vue')
      },
      {
        path: 'user-info',
        component: () => import('@/views/user/userInfo.vue')
      },
      {
        path: 'user-avatar',
        component: () => import('@/views/user/userAvatar.vue')
      },
      {
        path: 'user-pwd',
        component: () => import('@/views/user/userPwd.vue')
      },
      {
        path: 'art-cate',
        component: () => import('@/views/article/artCat.vue')
      },
      {
        path: 'art-list',
        component: () => import('@/views/article/artList.vue')
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    // 懒加载，进入路由路径过后才加载组件，页面加载的资源空间小，速度更快
    component: () => import('@/views/login/loginIndex')
  },
  {
    path: '/reg',
    name: 'register',
    component: () => import('@/views/register/registerIndex')
  }
  // {
  //   path: '/about',
  //   name: 'about',
  //   // route level code-splitting
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  // }
]

const router = new VueRouter({
  routes
})

// 全局前置路由守卫
router.beforeEach((to, from, next) => {
  // 离开主页时也会发请求，所以要判断是否vuex存在token
  // 当获得用户信息以后就不用再发请求了,退出登录以后也要清除userinfo
  // console.log(to, from)
  // 设置不能通过输入地址进入除登陆注册页面
  // 当有了token就视为登陆，可以进入登陆页面
  // next()强制切换路由地址，会再次走路由守卫去匹配路由表
  const whiteList = ['/login', '/reg']
  const token = store.state.token
  if (token) {
    if (!store.state.userInfo.username) {
      store.dispatch('getUserInfoActions')
    }
    next()
  } else {
    // next('/login')
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
